<?php 
namespace Wechat;
class Wechat{
	public $appid = 'wxcdda1146a79ce096';
	public $secret = 'acc71fe0e9c8376ebc2b5894674cc41c';
	/**
	 * [getRequestCodeUrl 获取获取code的url地址]
	 * @param  [type] $url           [授权后的跳转地址]
	 * @param  string $response_type [返回类型]
	 * @param  string $scope         [授权作用域]
	 * @param  [type] $state         [state参数]
	 * @return [type]                [带参数的url地址]
	 */
	public function getRequestCodeUrl($url,$response_type='code',$scope='snsapi_userinfo',$state=null){
		$url = urlencode($url);
		$str = "appid={$this->appid}&redirect_uri={$url}&response_type={$response_type}&scope={$scope}&state={$state}";
		return "https://open.weixin.qq.com/connect/oauth2/authorize?{$str}#wechat_redirect";
	}
	/**
	 * [getAccessToken 获取access_token]
	 * @param  [type] $code [对应的code]
	 * @return [type]       [用户token数据]
	 */
	public function getAccessToken($code){
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->secret}&code={$code}&grant_type=authorization_code";
		$result = userinfo($url);
		return $result;
	}

	public function getSubscribeToke(){
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->secret}";
		$result = userinfo($url);
		return $result;
	}
	public function getSubscribe($token,$openid){
		$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$openid}&lang=zh_CN";
		$result = userinfo($url);
		return $result;
	}
	/**
	 * [getUserInfo 获取用户信息]
	 * @param  [type] $access_token [用户的access_token]
	 * @param  [type] $openid       [用户的openid]
	 * @param  string $lang         [返回数据语言]
	 * @return [type]               [用户信息]
	 */
	public function getUserInfo($access_token,$openid,$lang='zh_CN'){
		$url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid=$openid&lang={$lang}";
		$result = userinfo($url);
		return $result;
	}
	/**
	 * [userinfo 获取微信请求数据]
	 * @param  [type] $url    [请求的url地址]
	 * @return [type]         [用户数据]
	 */
	public function userinfo($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);//获取url地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);//禁止服务器端验证
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);//证书与主机名是否一致
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//将执行的数据设置为返回而不是直接输出
        $output = json_decode(curl_exec($curl));//执行链接
        curl_close($curl);
        return $output;
    }
}

?>